# coding: utf-8
from datetime import datetime
from typing import List

from sqlalchemy import Column, String, TEXT, DATETIME, BOOLEAN
from sqlalchemy.orm import Session

from ...db import DbBase


class TabelHistory(DbBase):
    __tablename__ = 'history'

    name = Column(String(255), nullable=False)
    cover_url = Column(String(255), nullable=False, primary_key=True)
    video_url = Column(TEXT)
    vodid = Column(String(255))
    tags = Column(String(255))
    description = Column(TEXT)
    is_like = Column(BOOLEAN, default=0)
    create_time = Column(DATETIME, default=datetime.now())
    update_time = Column(DATETIME, default=datetime.now())


def history_exists(video_url: str, session: Session) -> bool:
    return session.query(TabelHistory).filter_by(video_url=video_url).count() > 0


def update_history(video_url: str, name: str, cover_url: str, tags: str, description: str, is_like: bool,
                   session: Session) -> None:
    history = session.query(TabelHistory).filter_by(video_url=video_url).first()
    if not history:
        return
    history.name = name
    history.cover_url = cover_url
    history.tags = tags
    history.description = description
    history.is_like = is_like
    history.update_time = datetime.now()
    session.commit()


def add_history(video_url: str, name: str, cover_url: str, tags: str, description: str, is_like: bool,
                session: Session) -> None:
    if history_exists(video_url, session):
        update_history(video_url, name, cover_url, tags, description, is_like, session)
        return
    history = TabelHistory(video_url=video_url, name=name, cover_url=cover_url, tags=tags, description=description,
                           is_like=is_like)
    session.add(history)
    session.commit()


def delete_history(video_url: str, session: Session) -> None:
    history = session.query(TabelHistory).filter_by(video_url=video_url).first()
    if not history:
        return
    session.delete(history)
    session.commit()


def get_history_list(session: Session) -> List[TabelHistory]:
    data = session.query(TabelHistory).all()
    return data